package com.youth.config;

import com.youth.feign.UserFeign;
import com.youth.result.ResultBean;
import com.youth.utils.MySpringUtil;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * @author wuxian
 * @date 2019/12/23 14:21
 */
public class MyRelam extends AuthorizingRealm {

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {

        String username = (String) principals.getPrimaryPrincipal();
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        UserFeign userFeign = MySpringUtil.getBean(UserFeign.class);
        //获取数据库用户角色
        ResultBean bean = userFeign.getUserRolesByName(username);
        if (null != bean) {
            Object data = bean.getData();
            if (null != data) {
                List<String> roles = (List<String>) data;
                if (!CollectionUtils.isEmpty(roles)) {
                    authorizationInfo.addRoles(roles);
                }
            }
        }
        //获取数据库用户权限
        ResultBean resultBean = userFeign.getUserPressionByName(username);
        if (null != resultBean) {
            Object data = resultBean.getData();
            if (null != data) {
                List<String> pression = (List<String>) data;
                if (!CollectionUtils.isEmpty(pression)) {
                    authorizationInfo.addStringPermissions(pression);
                }
            }
        }
        return authorizationInfo;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
//        //根据token获取用户名
//        String username = (String) token.getPrincipal();
//
//        User user = userService.getUserInfoByName(username);
//        if (user == null){
//            throw new AuthenticationException("此用户不存在");
//        } else {
//            SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(user, user.getPassword(), getName());
//            simpleAuthenticationInfo.setCredentialsSalt(ByteSource.Util.bytes(user.getUsername()));
//            return simpleAuthenticationInfo;
//        }
        return null;
    }
}
